<?php include_once 'header.php'; ?>
<style>
    .client-action {
        height: 25px !important;
        font-size: 10px !important;
        width: 10px !important;
        padding-top: 4px !important;
        margin-right: 5px;
    }

    .invoice {
        position: relative;
        width: 100%;
        margin: 0px auto;
        background: none repeat scroll 0% 0% #FFF;
        border: none;
    }

    .invoice-page-header {
        margin: 2px 0px 5px;
        font-size: 22px;
        padding-bottom: 0px;
        border-bottom: none;
    }

    #order-table {
        cursor: pointer;
    }

    #order-items > tr {
        cursor: pointer;
    }
</style>
<aside class="right-side">
    <section class="content-header">
        <h1>
            New Orders
            <small>Order Management</small>
        </h1>
        <ol class="breadcrumb">
            <li><a href="#"><i class="fa fa-truck"></i> Order Management</a></li>
            <li class="active">New Orders</li>
        </ol>
    </section>
    <section class="content">
        <div class="row">
            <div class="col-md-12">
                <div class="box box-primary">
                    <div class="box-header">
                        <h3 class="box-title"><i class="fa fa-truck"></i> Order Management</h3>

                        <div class="box-tools">
                            <div class="input-group">
                                <input type="text" name="table_search" class="form-control input-sm pull-right"
                                       style="width: 150px;" placeholder="Search"/>

                                <div class="input-group-btn">
                                    <button class="btn btn-sm btn-default"><i class="fa fa-search"></i></button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- /.box-header -->
                    <div class="box-body table-responsive no-padding" style="min-height:400px;">
                        <table id="order-table" class="table table-hover">
                            <tr>
                                <th style="width:100px;">Order No.</th>
                                <th style="width:150px;">Date</th>
                                <th style="width:250px;">Agency</th>
                                <th style="width:250px;">Agent Name</th>
                                <th style="width:100px;">Price</th>
                                <th>Action</th>
                            </tr>

                        </table>
                    </div>
                    <div class="overlay loader" style="display:none"></div>
                    <div class="loading-img loader" style="display: none"></div>
                    <!-- /.box-body -->
                </div>
                <!-- /.box -->
            </div>
        </div>
    </section>
</aside>
<div class="modal fade" id="myOrder" tabindex="-1" role="dialog" aria-labelledby="myOrderLabel" aria-hidden="true"
     data-backdrop="static">
    <div class="modal-dialog" style="width:800px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span
                        class="sr-only">Close</span></button>
                <h2 class="page-header invoice-page-header">
                    <i class="fa fa-globe"></i> &nbsp; Anmol Cards.
                    <small class="pull-right" style="margin-right: 10px !important">Order Date: <span
                            class="order-date-header"></span></small>
                </h2>
            </div>
            <div class="modal-body" style="padding:0px 0px 0px 0px;">
                <section class="content invoice" style="padding:10px 15px">
                    <div class="row invoice-info">
                        <div class="col-sm-4 invoice-col">
                            <address>
                                <strong><span class="client-business"></span></strong><br>
                                <span class="client-name"></span><br>
                                <span class="client-email"></span><br>
                            </address>
                        </div>
                        <div class="col-sm-4 invoice-col">
                        </div>
                        <div class="col-sm-4 invoice-col">
                            <b>Order No: </b><span class="order-id">  </span><br>
                            <b>Order Date: </b><span class="order-date"> </span>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-xs-12 table-responsive">
                            <table class="table table-striped">
                                <thead>
                                <tr>
                                    <th>Qty</th>
                                    <th>Branch</th>
                                    <th>Product Code</th>
                                    <th>Price (Per Unit)</th>
                                    <th>Discount</th>
                                    <th>Subtotal</th>
                                    <th>Action</th>
                                </tr>
                                </thead>
                                <tbody id="order-items">

                                </tbody>
                            </table>
                        </div>
                        <!-- /.col -->
                    </div>
                    <!-- /.row -->

                    <div class="row">
                        <div class="col-xs-6" style="margin-top: 80px;">
                            <div class="no-print">
                                <button class="btn btn-default" onclick=""><i class="fa fa-print"></i> Print</button>
                            </div>
                        </div>
                        <div class="col-xs-6" style="padding-right:86px;">
                            <div class="table-responsive">
                                <table class="table">
                                    <tbody>
                                    <tr>
                                        <th style="width:50%">Subtotal:</th>
                                        <td class="subtotal"></td>
                                    </tr>
                                    <tr>
                                        <th>Discount</th>
                                        <td class="discount"></td>
                                    </tr>
                                    <tr>
                                        <th>Total:</th>
                                        <td class="total"></td>
                                    </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>

                </section>
            </div>
            <div class="modal-footer">
                <button type="button" class=" pull-right btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
<?php include 'footer.php'; ?>
<script>
var LOCATIONDATA = JSON.parse('<?php echo json_encode($locations) ?>');

$(document).ready(function () {
    $(".loader").show();
    $.get("getOrders/NEW",function (response) {
        if (!response.error) {
            for (var i = 0; i < response.data.length; i++) {
                var order = response.data[i];


                var row = $("<tr id='order_" + order.id + "'></tr>");
                $(row).append($("<td class='order-row'></td>").text(order.id));
                $(row).append($("<td class='order-row'></td>").text(moment(order.orderDate.date).format('lll')));
                var agencyName = "NA";
                var agentName = "NA";
                if (order.agency != null) {
                    agencyName = order.agency.businessName;
                    agentName = order.agency.firstName + " " + order.agency.lastName;
                }
                $(row).append($("<td class='order-row'></td>").text(agencyName));
                $(row).append($("<td class='order-row'></td>").text(agentName));
                $(row).append($("<td class='order-row'></td>").text(order.price));

                var cancelButton = $("<button class='btn btn-danger ladda-button client-action order-cancel' data-style='slide-right' id='cancelbtn_" + order.id + "'><i class='fa fa-times'/></button>");
                var confirmButton = $("<button class='btn btn-success ladda-button client-action order-complete' data-style='slide-right' id='confirmbtn_" + order.id + "'><i class='fa fa-check'/></button>");
                var mailButton = $("<button class='btn btn-default client-action order-mail' id='btn-mail_" + order.id + "'><i class='fa fa-envelope'/></button>")

                var cell = $("<td></td>");
                $(cell).append(cancelButton);
                $(cell).append(confirmButton);
                $(cell).append(mailButton);
                $(row).append(cell);
                $("#order-table").append(row);
            }
        } else {
            errorAlert(response.errorMessage);
        }
    }).always(function () {
            $(".loader").hide();
        });

    $("body").on("click", "button.order-complete", function () {
        var orderId = $(this).parent().parent().attr("id");
        $.get("orderComplete/" + getElementId(orderId), function (response) {
            if (!response.error) {
                $("#" + orderId).hide();
                $("#" + orderId).remove();
            } else {
                errorAlert(response.errorMessage);
            }
        });
    });

    $("body").on("click", "button.order-cancel", function () {
        var orderId = $(this).parent().parent().attr("id");
        $.get("orderCancel/" + getElementId(orderId), function (response) {
            if (!response.error) {
                $("#" + orderId).hide();
                $("#" + orderId).remove();
            } else {
                errorAlert(response.errorMessage);
            }
        });
    });

    $("body").on("click", "td.order-row", function () {
        $("#order-table").css('cursor', 'progress');
        var orderId = getElementId($(this).parent("tr").attr("id"));
        $.get("getOrderDetails/" + orderId,function (response) {
            if (!response.error) {
                populateOrderDetails(response.data);
                $("#myOrder").modal("show");
            } else {
                errorAlert(response.errorMessage);
            }
        }).always(function () {
                $("#order-table").css('cursor', 'pointer');
            });
    });



    $("body").on("click", "button.item-edit", function () {
        $(this).attr('disabled', 'disabled');
        var parent = $(this).parent().parent();
        var itemId = $(parent).attr("id");
        var location = $(parent).find(".item-location").text();
        $(parent).addClass("action-item");
        $(parent).find(".item-quantity").html($("<input type='text' name='item-quantity' id='item-quantity' style='width:70px'></input>").val($(parent).find(".item-quantity").text()));
        $(parent).find(".item-discount").html($("<input type='text' name='item-discount' id='item-discount' style='width:50px'></input>").val($(parent).find(".item-discount").text()));

        var select = $("<select name='item-locaiton' id='item-location'></select>");
        for (var i = 0; i < LOCATIONDATA.length; i++) {
            var opt = $("<option></option>");
            $(opt).text(LOCATIONDATA[i].name);
            $(opt).attr("value", LOCATIONDATA[i].id);
            if (LOCATIONDATA[i].name.trim() === location.trim()) {
                $(opt).attr('selected', 'selected');
            }
            $(select).append(opt);
        }
        $(parent).find(".item-location").html(select);
    });

    $("body").on("click", "button.item-delete", function () {
        $(this).attr('disabled', 'disabled');
        var parent = $(this).parent().parent();
        var itemId = getElementId($(parent).attr("id"));
        var orderId = $("#myOrder").find(".order-id").text();
        $("#order-items").css('cursor', 'progress');
        $.get("deleteOrderItem/" + itemId + "/" + orderId,function (response) {
            if (!response.error) {
                populateOrderDetails(response.data.order);
            } else {
                errorAlert(response.errorMessage);
            }
        }).always(function () {
                $("#order-items").css('cursor', 'pointer');
            });
    });

    $("body").on("keypress", "tr.action-item", function (e) {
        if (e.keyCode == 13) {
            $("#order-items").css('cursor', 'progress');
            $(this).find(".item-edit").removeAttr('disabled');
            var itemId = getElementId($(this).attr("id"));
            var newQuantity = $(this).find("input[name=item-quantity]").val();
            var newDiscount = $(this).find("input[name=item-discount]").val();
            var newLocation = $(this).find("select[name=item-locaiton]").val();
            var orderId = $("#myOrder").find(".order-id").text();
            $.get("updateOrderItem/" + itemId + "/" + newQuantity + "/" + newDiscount + "/" + newLocation + "/" + orderId,function (response) {
                if (!response.error) {
                    populateOrderDetails(response.data.order);
                } else {
                    errorAlert(response.errorMessage);
                }
            }).always(function () {
                    $("#order-items").css('cursor', 'pointer');
                });
        }
    });
});

function populateOrderDetails(order) {
    var orderDiv = $("#myOrder");
    $(orderDiv).find(".order-id").text(order.id);
    $(orderDiv).find(".order-date-header").text(moment(order.orderDate.date).format('ll'));
    $(orderDiv).find(".order-date").text(moment(order.orderDate.date).format('lll'));

    $businessName = "NA";
    $agentName = "NA";
    $agentEmail = "NA";
    if (order.agency != null) {
        $businessName = order.agency.businessName;
        $agentName = order.agency.firstName + " " + order.agency.lastName;
        $agentEmail = order.agency.email;
    }
    $(orderDiv).find(".client-business").text($businessName);
    $(orderDiv).find(".client-name").text($agentName);
    $(orderDiv).find(".client-email").text($agentEmail);
    $("#order-items").html("");
    var subtotal = 0;
    for (var i = 0; i < order.orderItems.length; i++) {
        var item = order.orderItems[i];

        var row = $("<tr></tr>");
        $(row).attr("id", "item_" + item.id);
        $(row).append($("<td class='item-quantity'></td>").text(item.quantity));
        $(row).append($("<td class='item-location'></td>").text(item.branch.name));
        $(row).append($("<td></td>").text(item.product.name + " - " + item.product.category.name));
        $(row).append($("<td></td>").text(item.price));
        $(row).append($("<td class='item-discount'></td>").text(item.discount));
        $(row).append($("<td></td>").text(item.price * item.quantity));

        var actionCell = $("<td></td>");
        if (order.orderItems.length != 1) {
            $(actionCell).append("<button class='btn btn-danger ladda-button client-action item-delete' data-style='slide-right'><i class='fa fa-times'/></button>");
        }
        $(actionCell).append("<button class='btn btn-default ladda-button client-action item-edit' data-style='slide-right'><i class='fa fa-pencil'/></button>");

        $(row).append(actionCell);
        $("#order-items").append(row);
        subtotal += item.price * item.quantity;
    }

    $(orderDiv).find(".subtotal").text(subtotal);
    $(orderDiv).find(".discount").text(subtotal - order.price);
    $(orderDiv).find(".total").text(order.price);
}
</script>